/**
 * @Copyright 
 * @Project inetdisk
 * @CreateTime 2015-10-12 上午10:56:20
 */
package ren.wxyz.inetdisk.util;

import java.security.MessageDigest;
import java.util.Random;

import org.apache.commons.codec.digest.Crypt;

import com.alibaba.fastjson.JSON;

/**
 * <p>
 * 编码，转换，加密，解密工具类
 * </p>
 * @Author wxyz
 * @CreateTime 2015-10-12 上午10:56:20 init class
 */
public class DigitUtils {
	
	static final String B64T = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	
	/**
	 * <p>
	 * 字符串数据到MD5
	 * </p>
	 * @param data
	 * @return md5摘要
	 * @CreateTime 2015-10-12 上午11:21:25 create method
	 */
	public static String toMd5(String data) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = data.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;  
		}
	}
	
	/**
	 * <p>
	 * 生产固定位数的随机盐值
	 * </p>
	 * @param num 盐值长度
	 * @return 随机盐值
	 * @CreateTime 2015-11-6 下午5:01:00 create method
	 */
	public static String getRandomSalt(final int num) {
        final StringBuilder saltString = new StringBuilder();
        for (int i = 1; i <= num; i++) {
            saltString.append(B64T.charAt(new Random().nextInt(B64T.length())));
        }
        return saltString.toString();
    }
	
	/**
	 * <p>
	 * 计算密码的SHA-256摘要
	 * </p>
	 * @param passwd 密码
	 * @param pwdSalt 密码的盐值
	 * @return 密码的摘要
	 * @CreateTime 2015-10-29 上午10:23:05 create method
	 */
	public static String cryptPwd(String passwd, String pwdSalt) {
		if (null == passwd) {
			return "";
		}
		
		// 添加加密级别，5代表sha-256
		String salt = "$5$" + pwdSalt;
		
		// 得到密文
		String ciphertext = Crypt.crypt(passwd, salt);
		
		return ciphertext.replace(salt + "$", "") + "==";
	}
	
	/**
	 * <p>
	 * 将对象序列化成字符串
	 * </p>
	 * @param obj 对象
	 * @return
	 * @CreateTime 2015-10-23 下午5:17:10 create method
	 */
	public static String toJson(Object obj) {
		return JSON.toJSONString(obj);
	}
	
	/**
	 * <p>
	 * 将json串反序列化成对象
	 * </p>
	 * @param json 字符串
	 * @return
	 * @CreateTime 2015-10-23 下午5:17:43 create method
	 */
	public static <T> T JsontoObject(String json, Class<T> clz) {
		return JSON.parseObject(json, clz);
	}
}
